from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.authentication import jwt_decode_handler

from xyz.models import Spit
from xyz.serializers.spit import SpitInfoModelSerializer


class SpitInfoView(APIView):
    def get(self, request, id):
        spit = Spit.objects.get(id=id)
        serializer = SpitInfoModelSerializer(spit)
        try:

            token = self.request.auth

            token_user = jwt_decode_handler(token)

            user_id = token_user['user_id']

        except Exception as e:

            return Response(status=404)

        redis_conn = get_redis_connection('spit')
        if redis_conn.sismember('thumbup_%s' % id, user_id):
            hasthumbup = True
        else:
            hasthumbup = False

        serializer.data['hasthumbup'] = hasthumbup
        return Response(dict(serializer.data, **{'hasthumbup': hasthumbup}))
